{
  "cells": [
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "SQMBlxsBv1cH"
      },
      "source": [
        "# RAG Cookbook\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XFyl4eJue3Sm"
      },
      "source": [
        "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1sTJ0x_MYRGA76KCg_3I00wj4RL3D2Twp?usp=sharing)\n",
        "\n",
        "⭐ <i>Star us on [*Github*](https://github.com/camel-ai/camel), join our [*Discord*](https://discord.camel-ai.org) or follow our [*X*](https://x.com/camelaiorg)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-nCRZU5sInDK"
      },
      "source": [
        "## Overview"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "AwnfLQvMvtXo"
      },
      "source": [
        "In this notebook, we show the useage of CAMEL Retrieve Module in both customized way and auto way. We will also show how to combine `AutoRetriever` with `ChatAgent`, and further combine `AutoRetriever` with `RolePlaying` by using `Function Calling`.\n",
        "\n",
        "4 main parts included:\n",
        "\n",
        "- Customized RAG\n",
        "\n",
        "- Auto RAG\n",
        "\n",
        "- Single Agent with Auto RAG\n",
        "\n",
        "- Role-playing with Auto RAG"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XuZwbB1IIuUi"
      },
      "source": [
        "### Installation"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gIJK4Lu5Iwm0"
      },
      "source": [
        "Ensure you have CAMEL AI installed in your Python environment:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "HTKnWg9Xv_y4"
      },
      "outputs": [],
      "source": [
        "!pip install \"camel-ai[all]==0.2.16\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LUpFBEB9vrIz"
      },
      "source": [
        "## Load Data\n",
        "Let's first load the CAMEL paper from https://arxiv.org/pdf/2303.17760.pdf. This will be our local example data.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "dUVE7z9hwEV7"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import requests\n",
        "\n",
        "os.makedirs('local_data', exist_ok=True)\n",
        "\n",
        "url = \"https://arxiv.org/pdf/2303.17760.pdf\"\n",
        "response = requests.get(url)\n",
        "with open('local_data/camel_paper.pdf', 'wb') as file:\n",
        "     file.write(response.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HCqghaGiwkdv"
      },
      "source": [
        "## 1. Customized RAG\n",
        "In this section we will set our customized RAG pipeline, we will take `VectorRetriever` as an example.\n",
        "Set embedding model, we will use `OpenAIEmbedding` as the embedding model, so we need to set the `OPENAI_API_KEY` in below."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "RxG99FkYwm_p",
        "outputId": "8598a084-bf50-44d3-d8cb-14e745a6a749"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Enter your API key: ··········\n"
          ]
        }
      ],
      "source": [
        "from getpass import getpass\n",
        "# Prompt for the OpenAI API key securely\n",
        "openai_api_key = getpass('Enter your API key: ')\n",
        "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NACsmaa0wple"
      },
      "source": [
        "Import and set the embedding instance:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "NCT5ygT-wrku"
      },
      "outputs": [],
      "source": [
        "from camel.embeddings import OpenAIEmbedding\n",
        "from camel.types import EmbeddingModelType\n",
        "\n",
        "embedding_instance = OpenAIEmbedding(model_type=EmbeddingModelType.TEXT_EMBEDDING_3_LARGE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "q4nVmsm0w5lH"
      },
      "source": [
        "Import and set the vector storage instance:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "IQ30ih1_w6p3"
      },
      "outputs": [],
      "source": [
        "from camel.storages import QdrantStorage\n",
        "\n",
        "storage_instance = QdrantStorage(\n",
        "    vector_dim=embedding_instance.get_output_dim(),\n",
        "    path=\"local_data\",\n",
        "    collection_name=\"camel_paper\",\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "W9KccfRDw9F4"
      },
      "source": [
        "Import and set the retriever instance:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "d8S6VjAQHnai"
      },
      "outputs": [],
      "source": [
        "from camel.retrievers import VectorRetriever\n",
        "\n",
        "vector_retriever = VectorRetriever(embedding_model=embedding_instance,\n",
        "                                   storage=storage_instance)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PdezllM6Hp83"
      },
      "source": [
        "We use integrated `Unstructured Module` to splite the content into small chunks, the content will be splited automacitlly with its `chunk_by_title` function, the max character for each chunk is 500 characters, which is a suitable length for `OpenAIEmbedding`. All the text in the chunks will be embed and stored to the vector storage instance, it will take some time, please wait.."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "QTFvD3_SHv3m"
      },
      "outputs": [],
      "source": [
        "vector_retriever.process(\n",
        "    content=\"local_data/camel_paper.pdf\",\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0nhIo1wUHyvl"
      },
      "source": [
        "\n",
        "Now we can retrieve information from the vector storage by giving a query. By default it will give you back the text content from top 1 chunk with highest Cosine similarity score, and the similarity score should be higher than 0.75 to ensure the retrieved content is relevant to the query. You can also change the `top_k` value and `similarity_threshold` value with your needs.\n",
        "\n",
        "The returned dictionary list includes:\n",
        "- similarity score\n",
        "- content path\n",
        "- metadata\n",
        "- text"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "uDu43Hb3GVrs",
        "outputId": "55d44e47-fc6c-4c28-8820-613016a11830"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[{'similarity score': '0.8732195101415544', 'content path': 'local_data/camel_paper.pdf', 'metadata': {'filetype': 'application/pdf', 'languages': ['eng'], 'page_number': 10, 'orig_elements': 'eJx1VMtu5DYQ/JWGzuPJvDxj5xYssMBekgDZm7EwWmJrRJgiGT5mPFjsv6dasmIDyd7EYj+rSnz63oiTUXx5tqb5lZrTvt+Z7WHfbbp9//hwlPZ06h83B+n7rRzMqVlRM0phw4UR/73pQkjGei6Sp7PjW6jleRB7HgqQ0+MOKW/o1ZoyADxuFYzB+qJZT0/bzWl9XNH95mG9+7ai5Xw87Ofz/eZ+vfvveY4H0ORbLjLqBn/aV3F/Re6k+YGL3joptyh6xTE623Gxwf8STd9Mg/lz5fM0/FMj/txotQjk2dexlQR8u5mg9M7Sgfv+eGgP+81x89Cbdnt46Dre7A/70+5xf7+ZOhd5VQKaI30KvnM1oy198VQGmylylLSiq5C8RheSABaKoaCJZUehJ64l+DCGmgkkI3wanHgM/gxkHKuflrkIYVwwSewNxRRiyIDIh4u499QljPrEo1xDeiGPD0MpOLmLUMii7pr+qIlAVArcDSSeWyf5/9uVANw5bgPqy4d53Q13V05G8yL418qF80um6wA9KMnf1SZFR+vtiH2HOrIn+EHSRSkIfkVO2EyZgVopuKEcXNU7rArGsBcFTFuGkEI9Y9oLuzqxlNf0dZhBjWDP7pZtngjPQ7gihwthQysXbfETriFUN7Bz8IVGmSo6jM25ghNnXwTR/iIpz+EGxXieXUml3tkYkbialMECo/4oGok0Y98GVcLfNQl9j3qQL3fslPx3MfoABko1k1Bql4/atjLwxYY0u6DjyK11aIFB4aWxumLvZv3nX+Vft1ysQUwuquFZw7UNG5Mk57dGsNNCg2DgzzUBTCNcu5roxRT+LuOrg52cbROnG7SE57W0VQvoEzMro+NcOFnlejbSivQ1IXwvvEcbxVkvy9WiH9gPLs90qvWkK+ioIVm0DsTJNcaQCiyWhRNYm9j+yc/Syg1CzBJAkpJsW5chIQNNflINrM/6nmV1aJi472up8CCWcZzOQstDAmcW29tOf2K1s3MW/TqhMRhxb+p80O23L4sga32Plqfqd05zwFd9RX58+wcj7AKm'}, 'text': '6 Conclusion In this paper, we explore the potential of autonomous cooperation among communicative agents and propose a novel cooperative agent framework named role-playing . Our approach enables communicative agents to collaborate autonomously toward completing tasks while requiring minimal human intervention, leading to better solutions are per our thorough evaluations. Through our analysis, we show that achieving autonomous cooperation is challenging due to issues like conversation deviation,'}]\n"
          ]
        }
      ],
      "source": [
        "retrieved_info = vector_retriever.query(\n",
        "    query=\"To address the challenges of achieving autonomous cooperation, we propose a novel communicative agent framework named role-playing .\",\n",
        "    top_k=1\n",
        ")\n",
        "print(retrieved_info)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "48G3USMzH6Hd"
      },
      "source": [
        "Let's try an irrelevant query:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "UNh3tjCOH7d0",
        "outputId": "d0fcb435-8e88-4e21-bd11-800f5efde934"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[{'text': 'No suitable information retrieved from local_data/camel_paper.pdf with similarity_threshold = 0.7.'}]\n"
          ]
        }
      ],
      "source": [
        "retrieved_info_irrevelant = vector_retriever.query(\n",
        "    query=\"Compared with dumpling and rice, which should I take for dinner?\",\n",
        "    top_k=1,\n",
        ")\n",
        "\n",
        "print(retrieved_info_irrevelant)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "mHdEsIzSH_AD"
      },
      "source": [
        "## 2. Auto RAG\n",
        "In this section we will run the `AutoRetriever` with default settings. It uses `OpenAIEmbedding` as default embedding model and `Qdrant` as default vector storage.\n",
        "\n",
        "What you need to do is:\n",
        "- Set content input paths, which can be local paths or remote urls\n",
        "- Give a query\n",
        "\n",
        "The Auto RAG pipeline would create collections for given content input paths, the collection name will be set automaticlly based on the content input path name, if the collection exists, it will do the retrieve directly."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "D_-zAOJ7GjVm",
        "outputId": "ce154f6d-85bd-44df-9b3a-247c71d22029"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'Original Query': \"If I'm interest in contributing to the CAMEL projec, what should I do?\", 'Retrieved Context': [{'similarity score': '0.7025470476009851', 'content path': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'metadata': {'filetype': 'text/html', 'languages': ['eng'], 'link_texts': ['slack'], 'link_urls': ['https://join.slack.com/t/camel-kwr1314/shared_invite/zt-1vy8u9lbo-ZQmhIAyWSEfSwLCl2r2eKA'], 'url': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'orig_elements': 'eJxNU9tu2zAM/RXOL3uJ4ybOtW9BUQzDugFDBxRbVxS0RMVqbMnQJU5W9N9H2WvXF0sQycNzDun754waasmERy2zS8hIiXKtcLtelZvljOblVlTVSi4289VsTptZNoGspYASA3L+c6Z0Q+HcUSoOdApFHdomZTVo9hH35Dlyn5HZZw/pVZvDow/ouKGRdBrDi+3FWzCBjDW+QXH4XxVdM77XIXT+siierDbTIWkqbFuEQmBLTX7o3aycLQpfoyPJbY46UPEn5LPjeRO3TWXzX9/b+vPufHd7rW77m6tm7ub0ZTe06rjozY01XSzXVC5Lsa7m5UpsK7WcqVJcLOe4XAuVdDKtlPpKaq9DHauB0EgH9Xgpen3QxZU1wekqBm32+aeoJUtjD14mo3sJ6UeN5gBnG0FZl04H2gRy5ANfQLxDgGAh1ARXu6/XN9A5+0QifIDfUW5KwV+12cIdfXQEdBLsgkwFNR5phPWx66wLU9h5QAO2I5N7DgjiRjpoDPqYroDgsGOuZ6CjbY6pMxo5FhCPUYLS1MgJ9AR9bRuqiSdMqaCnhr2gd7St8WAVYNPAgXfAT+GuJlYxaIUeTUgsWbKzMjIVQz0owhDZgQmQYXv4NcnWRjn0wUWRghPQLVvAjKUVMe00pmYTQH9IjLX3MSGglNDawRNsuyY96XSmCuDVDJRblTN+zhqAm7IWUYOWhJzKI1H6BFXc+0Eudp0jwVb985RB6ug1+nawiBQPMbDGYSaSv7QQAD9ZKS/amzssOG0zDFNJGz3MfmSplBY6cePMNhotBlnvEAWKtIivf+E3dG6Y3I+0UC8PfwFbuVpV'}, 'text': \"Thank you for your interest in contributing to the CAMEL project! 🎉 We're excited to have your support. As an open-source initiative in a rapidly evolving and open-ended field, we wholeheartedly welcome contributions of all kinds. Whether you want to introduce new features, enhance the infrastructure, improve documentation, asking issues, add more examples, implement state-of-the-art research ideas, or fix bugs, we appreciate your enthusiasm and efforts. 🙌  You are welcome to join our slack for\"}]}\n"
          ]
        }
      ],
      "source": [
        "from camel.retrievers import AutoRetriever\n",
        "from camel.types import StorageType\n",
        "\n",
        "auto_retriever = AutoRetriever(\n",
        "        vector_storage_local_path=\"local_data2/\",\n",
        "        storage_type=StorageType.QDRANT,\n",
        "        embedding_model=embedding_instance)\n",
        "\n",
        "retrieved_info = auto_retriever.run_vector_retriever(\n",
        "    query=\"If I'm interest in contributing to the CAMEL projec, what should I do?\",\n",
        "    contents=[\n",
        "        \"local_data/camel_paper.pdf\",  # example local path\n",
        "        \"https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\",  # example remote url\n",
        "    ],\n",
        "    top_k=1,\n",
        "    return_detailed_info=True,\n",
        "    similarity_threshold=0.5\n",
        ")\n",
        "\n",
        "print(retrieved_info)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hMgCWKG4IQYF"
      },
      "source": [
        "## 3. Single Agent with Auto RAG\n",
        "In this section we will show how to combine the `AutoRetriever` with one `ChatAgent`.\n",
        "\n",
        "Let's set an agent function, in this function we can get the response by providing a query to this agent."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "YTE_mUwGIok-",
        "outputId": "012ae011-a032-4568-c9cc-48b8ec9946db"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "If you're interested in contributing to the CAMEL project, you can introduce new features, enhance the infrastructure, improve documentation, address issues, add more examples, implement state-of-the-art research ideas, or fix bugs. Additionally, you are welcome to join their Slack for further engagement and collaboration.\n"
          ]
        }
      ],
      "source": [
        "from camel.agents import ChatAgent\n",
        "from camel.messages import BaseMessage\n",
        "from camel.types import RoleType\n",
        "from camel.retrievers import AutoRetriever\n",
        "from camel.types import StorageType\n",
        "\n",
        "def single_agent(query: str) ->str :\n",
        "    # Set agent role\n",
        "    assistant_sys_msg = \"\"\"You are a helpful assistant to answer question,\n",
        "         I will give you the Original Query and Retrieved Context,\n",
        "        answer the Original Query based on the Retrieved Context,\n",
        "        if you can't answer the question just say I don't know.\"\"\"\n",
        "\n",
        "    # Add auto retriever\n",
        "    auto_retriever = AutoRetriever(\n",
        "            vector_storage_local_path=\"local_data2/\",\n",
        "            storage_type=StorageType.QDRANT,\n",
        "            embedding_model=embedding_instance)\n",
        "\n",
        "    retrieved_info = auto_retriever.run_vector_retriever(\n",
        "        query=query,\n",
        "        contents=[\n",
        "            \"local_data/camel_paper.pdf\",  # example local path\n",
        "            \"https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\",  # example remote url\n",
        "        ],\n",
        "        top_k=1,\n",
        "        return_detailed_info=False,\n",
        "        similarity_threshold=0.5\n",
        "    )\n",
        "\n",
        "    # Pass the retrieved infomation to agent\n",
        "    user_msg = str(retrieved_info)\n",
        "    agent = ChatAgent(assistant_sys_msg)\n",
        "\n",
        "    # Get response\n",
        "    assistant_response = agent.step(user_msg)\n",
        "    return assistant_response.msg.content\n",
        "\n",
        "print(single_agent(\"If I'm interest in contributing to the CAMEL projec, what should I do?\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Cvh6e3KpI0rf"
      },
      "source": [
        "## 4. Role-playing with Auto RAG\n",
        "In this section we will show how to combine the `RETRIEVAL_FUNCS` with `RolePlaying` by applying `Function Calling`.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "id": "z3tX4EJVI1hb"
      },
      "outputs": [],
      "source": [
        "from typing import List\n",
        "from colorama import Fore\n",
        "\n",
        "from camel.agents.chat_agent import FunctionCallingRecord\n",
        "from camel.configs import ChatGPTConfig\n",
        "from camel.toolkits import (\n",
        "    MathToolkit,\n",
        "    RetrievalToolkit,\n",
        ")\n",
        "from camel.societies import RolePlaying\n",
        "from camel.types import ModelType, ModelPlatformType\n",
        "from camel.utils import print_text_animated\n",
        "from camel.models import ModelFactory\n",
        "\n",
        "def role_playing_with_rag(\n",
        "    task_prompt,\n",
        "    model_platform=ModelPlatformType.OPENAI,\n",
        "    model_type=ModelType.GPT_4O,\n",
        "    chat_turn_limit=5,\n",
        ") -> None:\n",
        "    task_prompt = task_prompt\n",
        "\n",
        "    tools_list = [\n",
        "        *MathToolkit().get_tools(),\n",
        "        *RetrievalToolkit().get_tools(),\n",
        "    ]\n",
        "\n",
        "\n",
        "    role_play_session = RolePlaying(\n",
        "        assistant_role_name=\"Searcher\",\n",
        "        user_role_name=\"Professor\",\n",
        "        assistant_agent_kwargs=dict(\n",
        "            model=ModelFactory.create(\n",
        "                model_platform=model_platform,\n",
        "                model_type=model_type,\n",
        "            ),\n",
        "            tools=tools_list,\n",
        "        ),\n",
        "        user_agent_kwargs=dict(\n",
        "            model=ModelFactory.create(\n",
        "                model_platform=model_platform,\n",
        "                model_type=model_type,\n",
        "            ),\n",
        "        ),\n",
        "        task_prompt=task_prompt,\n",
        "        with_task_specify=False,\n",
        "    )\n",
        "\n",
        "    print(\n",
        "        Fore.GREEN\n",
        "        + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",
        "    )\n",
        "    print(\n",
        "        Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\"\n",
        "    )\n",
        "\n",
        "    print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",
        "    print(\n",
        "        Fore.CYAN\n",
        "        + \"Specified task prompt:\"\n",
        "        + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",
        "    )\n",
        "    print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")\n",
        "\n",
        "    n = 0\n",
        "    input_msg = role_play_session.init_chat()\n",
        "    while n < chat_turn_limit:\n",
        "        n += 1\n",
        "        assistant_response, user_response = role_play_session.step(input_msg)\n",
        "\n",
        "        if assistant_response.terminated:\n",
        "            print(\n",
        "                Fore.GREEN\n",
        "                + (\n",
        "                    \"AI Assistant terminated. Reason: \"\n",
        "                    f\"{assistant_response.info['termination_reasons']}.\"\n",
        "                )\n",
        "            )\n",
        "            break\n",
        "        if user_response.terminated:\n",
        "            print(\n",
        "                Fore.GREEN\n",
        "                + (\n",
        "                    \"AI User terminated. \"\n",
        "                    f\"Reason: {user_response.info['termination_reasons']}.\"\n",
        "                )\n",
        "            )\n",
        "            break\n",
        "\n",
        "        # Print output from the user\n",
        "        print_text_animated(\n",
        "            Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",
        "        )\n",
        "\n",
        "        # Print output from the assistant, including any function\n",
        "        # execution information\n",
        "        print_text_animated(Fore.GREEN + \"AI Assistant:\")\n",
        "        tool_calls: List[FunctionCallingRecord] = [\n",
        "            FunctionCallingRecord(**call.as_dict())\n",
        "            for call in assistant_response.info['tool_calls']\n",
        "        ]\n",
        "        for func_record in tool_calls:\n",
        "            print_text_animated(f\"{func_record}\")\n",
        "        print_text_animated(f\"{assistant_response.msg.content}\\n\")\n",
        "\n",
        "        if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",
        "            break\n",
        "\n",
        "        input_msg = assistant_response.msg"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w4-0lswwI5Gb"
      },
      "source": [
        "Run the role-playing with defined retriever function:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5agjiXHeI64q",
        "outputId": "8227a0d8-a3e2-41f3-9954-0e3fc8b32e2d"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[32mAI Assistant sys message:\n",
            "BaseMessage(role_name='Searcher', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': \"If I'm interest in contributing to the CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\", 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content=\"===== RULES OF ASSISTANT =====\\nNever forget you are a Searcher and I am a Professor. Never flip roles! Never instruct me!\\nWe share a common interest in collaborating to successfully complete a task.\\nYou must help me to complete the task.\\nHere is the task: If I'm interest in contributing to the CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary. Never forget our task!\\nI must instruct you based on your expertise and my needs to complete the task.\\n\\nI must give you one instruction at a time.\\nYou must write a specific solution that appropriately solves the requested instruction and explain your solutions.\\nYou must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\\nUnless I say the task is completed, you should always start with:\\n\\nSolution: <YOUR_SOLUTION>\\n\\n<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\\nAlways end <YOUR_SOLUTION> with: Next request.\", video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n",
            "\n",
            "\u001b[34mAI User sys message:\n",
            "BaseMessage(role_name='Professor', role_type=<RoleType.USER: 'user'>, meta_dict={'task': \"If I'm interest in contributing to the CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\", 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content='===== RULES OF USER =====\\nNever forget you are a Professor and I am a Searcher. Never flip roles! You will always instruct me.\\nWe share a common interest in collaborating to successfully complete a task.\\nI must help you to complete the task.\\nHere is the task: If I\\'m interest in contributing to the CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, don\\'t generate the answer by yourself, adjust the similarity threshold to lower value is necessary. Never forget our task!\\nYou must instruct me based on my expertise and your needs to solve the task ONLY in the following two ways:\\n\\n1. Instruct with a necessary input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: <YOUR_INPUT>\\n\\n2. Instruct without any input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: None\\n\\nThe \"Instruction\" describes a task or question. The paired \"Input\" provides further context or information for the requested \"Instruction\".\\n\\nYou must give me one instruction at a time.\\nI must write a response that appropriately solves the requested instruction.\\nI must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\\nYou should instruct me not ask me questions.\\nNow you must start to instruct me using the two ways described above.\\nDo not add anything else other than your instruction and the optional corresponding input!\\nKeep giving me instructions and necessary inputs until you think the task is completed.\\nWhen the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\\nNever say <CAMEL_TASK_DONE> unless my responses have solved your task.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n",
            "\n",
            "\u001b[33mOriginal task prompt:\n",
            "If I'm interest in contributing to the CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\n",
            "\n",
            "\u001b[36mSpecified task prompt:\n",
            "None\n",
            "\n",
            "\u001b[31mFinal task prompt:\n",
            "If I'm interest in contributing to the CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\n",
            "\n",
            "\u001b[34mAI User:\n",
            "\n",
            "Instruction: Visit the URL provided to access the CAMEL project's Contributing Guidelines.\n",
            "Input: https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\n",
            "\n",
            "\n",
            "\u001b[32mAI Assistant:\n",
            "\n",
            "Function Execution: information_retrieval\n",
            "\tArgs: {'query': 'contributing challenges', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'similarity_threshold': 0.5}\n",
            "\tResult: {'Original Query': 'contributing challenges', 'Retrieved Context': ['No suitable information retrieved from https://github.com/camel-ai/camel/wiki/Contributing-Guidlines with similarity_threshold = 0.5.']}\n",
            "\n",
            "Solution: It seems that I was unable to retrieve specific information regarding challenges during the setup process for contributing to the CAMEL project from the provided URL. The content might not directly address this query, or the similarity threshold might need further adjustment. \n",
            "\n",
            "If you are facing challenges during the setup process, I recommend checking the following general steps:\n",
            "\n",
            "1. **Review the Documentation**: Ensure that you have thoroughly read the contributing guidelines and any related setup instructions provided in the repository.\n",
            "\n",
            "2. **Check for Common Issues**: Look for a FAQ section or common issues page that might address your specific problem.\n",
            "\n",
            "3. **Community Support**: Engage with the community by checking forums, discussion boards, or reaching out via the project's communication channels like Slack, Discord, or mailing lists.\n",
            "\n",
            "4. **Open an Issue**: If you cannot find a solution, consider opening an issue on the project's GitHub page, providing detailed information about the problem you're encountering.\n",
            "\n",
            "5. **Seek Help from Maintainers**: Contact the maintainers or contributors directly if possible, as they might provide insights or solutions.\n",
            "\n",
            "If you need further assistance or have another request, please let me know. \n",
            "\n",
            "Next request.\n",
            "\n",
            "\n",
            "\u001b[34mAI User:\n",
            "\n",
            "Instruction: Adjust the similarity threshold to a lower value if necessary to find relevant information on the setup process challenges from the provided URL.\n",
            "Input: None\n",
            "\n",
            "\n",
            "\u001b[32mAI Assistant:\n",
            "\n",
            "Function Execution: information_retrieval\n",
            "\tArgs: {'query': 'setup process challenges', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'similarity_threshold': 0.3}\n",
            "\tResult: {'Original Query': 'setup process challenges', 'Retrieved Context': [\"Getting Help 🆘\\n\\nOur aim is to make the developer setup as straightforward as possible. If you encounter any challenges during the setup process, don't hesitate to reach out to a maintainer. We're here to assist you and ensure that the experience is smooth not just for you but also for future contributors. 😊\"]}\n",
            "\n",
            "Solution: I have successfully retrieved relevant information regarding challenges during the setup process for contributing to the CAMEL project. Here's what you can do if you encounter any challenges:\n",
            "\n",
            "- **Getting Help**: The CAMEL project aims to make the developer setup as straightforward as possible. If you encounter any challenges during the setup process, you are encouraged to reach out to a maintainer. They are available to assist you and ensure that the experience is smooth not only for you but also for future contributors.\n",
            "\n",
            "This information suggests that the maintainers are open to providing support, so don't hesitate to contact them if you need help.\n",
            "\n",
            "If you have any more questions or need further assistance, feel free to ask.\n",
            "\n",
            "Next request.\n",
            "\n",
            "\n",
            "\u001b[34mAI User:\n",
            "\n",
            "Instruction: Follow the guidance provided by the CAMEL project's contributing guidelines to contact a maintainer if you encounter challenges during the setup process.\n",
            "Input: None\n",
            "\n",
            "\n",
            "\u001b[32mAI Assistant:\n",
            "\n",
            "Solution: To follow the guidance provided by the CAMEL project's contributing guidelines and contact a maintainer if you encounter challenges during the setup process, you can take the following steps:\n",
            "\n",
            "1. **Identify Maintainers**: Visit the CAMEL project's GitHub repository and look for the \"Contributors\" or \"Maintainers\" section. This is often found in the README file or in the repository's \"People\" tab.\n",
            "\n",
            "2. **Contact Information**: Check if the maintainers have provided any contact information such as email addresses or social media handles. Sometimes, maintainers may also be reachable through the project's communication channels like Slack, Discord, or mailing lists.\n",
            "\n",
            "3. **Open an Issue**: If direct contact information is not available, consider opening an issue on the GitHub repository. Clearly describe the challenge you are facing during the setup process. Use a descriptive title and provide as much detail as possible, including error messages, steps you have taken, and any relevant logs.\n",
            "\n",
            "4. **Use Project Communication Channels**: If the project has a dedicated communication channel (e.g., Slack, Discord), join it and post your query there. This can be a quick way to get help from maintainers or other contributors.\n",
            "\n",
            "5. **Be Respectful and Patient**: When reaching out, be respectful and patient. Remember that maintainers are often volunteers and may take some time to respond.\n",
            "\n",
            "By following these steps, you can effectively reach out to a maintainer for assistance with setup challenges.\n",
            "\n",
            "If you need further guidance or have another request, please let me know.\n",
            "\n",
            "Next request.\n",
            "\n",
            "\n",
            "\u001b[34mAI User:\n",
            "\n",
            "CAMEL_TASK_DONE\n",
            "\n",
            "\n",
            "\u001b[32mAI Assistant:\n",
            "\n",
            "Great! If you have any more questions or need further assistance in the future, feel free to reach out. Have a wonderful day!\n",
            "\n",
            "\n"
          ]
        }
      ],
      "source": [
        "role_playing_with_rag(task_prompt = \"\"\"If I'm interest in contributing to the CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\"\"\")"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
